import {
  primaryBackgroundColor2,
  primaryColor2,
} from '../../../../theme/default';
import {useEffect, useState} from 'react';
import {ViewStyle, FlatList, Dimensions, RefreshControl} from 'react-native';

import {NavigationProp} from '@react-navigation/native';

import {UserToken} from '../../../../db/models/userTokenModel';
import {useSolanaClientProvider} from '../../../../hooks/useSolana/useSolanaClientProvider';
import {useSolanaOwnerTokenAccountsProvider} from '../../../../hooks/useSolana/useSolanaOwnerTokenAccounts';
import {useSolanaTokenListProvider} from '../../../../hooks/useSolana/useSolanaTokenListProvider';
import {useAccountProvider} from '../../../../hooks/useAccountProvider';
import {RootStackParamList} from '../../../Nav/routes';
import {TokenItem} from './TokenItem';

type TokenListProp = {
  customStyle?: ViewStyle;
  itemCustomStyle?: ViewStyle;
  onItemPress?: (item: UserToken) => void;
};
type RootStackNavigationProp = NavigationProp<RootStackParamList>;

const {width} = Dimensions.get('window');

export function TokenList({
  customStyle,
  itemCustomStyle,
  onItemPress,
}: Readonly<TokenListProp>) {
  const {userInfo} = useAccountProvider();

  const {solanaClient} = useSolanaClientProvider();
  const {solanaTokenList} = useSolanaTokenListProvider();

  const {accountsloading, userTokens, getTokenAccounts} =
    useSolanaOwnerTokenAccountsProvider();
    

  const [refreshing, setRefreshing] = useState<boolean>(false);

  useEffect(() => {
    if (userInfo !== undefined && solanaClient !== undefined) {
      getTokenAccounts();
    }
  }, [userInfo, solanaClient, solanaTokenList, getTokenAccounts]);

  const onRefresh = () => {
    setRefreshing(true);
    getTokenAccounts();
  };

  useEffect(() => {
    if (!accountsloading) {
      setRefreshing(false);
    }
  }, [accountsloading]);

  const handleItemPress = (item: UserToken) => {
    onItemPress != undefined && onItemPress(item);
  };

  const renderTokenItem = ({item}: {item: UserToken}) => (
    <TokenItem
      key={item.address}
      customStyle={{
        backgroundColor: primaryBackgroundColor2,
        borderRadius: 16,
      }}
      userToken={item}
      onPress={() => handleItemPress(item)}></TokenItem>
  );
  return (
    <FlatList
      showsVerticalScrollIndicator={false}
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={onRefresh}
          colors={[primaryColor2]} // Android: Circle colors
          tintColor={primaryColor2}
        />
      }
      style={{width: width - 32}}
      data={userTokens}
      renderItem={renderTokenItem}
      keyExtractor={item => item.address}
    />
  );
}
